/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package readfilesusingnio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SONGOKU20
 */
public class ReadFilesUsingNIO {
    //ReadFile Using NIO
    public static void WriteFileNIO(String FileName) throws IOException{
        try (FileOutputStream output = new FileOutputStream(FileName, true); FileChannel fchan = output.getChannel()) { 
            String data;
            Scanner input=new Scanner(System.in);
            System.out.println("Nhap vao doan can them vao file: ");
            data=input.nextLine();
            ByteBuffer buff = ByteBuffer.allocateDirect(data.length());
            buff.put(buff);
            buff.rewind();
            if(fchan.isOpen()) fchan.write(buff);
            buff.clear();
        }
        catch(Exception e){
            System.out.println("Khong ghi duoc file!!");
        }
    }
    private static void readFilesNIO(String fileName) {        
         try{
         Path path = Paths.get(fileName);
         // read file to byte array
         byte[] bytes = Files.readAllBytes(path);
         // read file to String list
         List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
         for (String line : allLines) {
              System.out.println(line);
         }
         }
         catch(Exception e){
             System.out.println("Khong tim duoc file!!");
         }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner input=new Scanner(System.in);
        System.out.println("Nhap file dau vao: ");
        String filename=input.nextLine();
        readFilesNIO(filename);
        System.out.println("Nhap file dau ra: ");
        String Filename=input.nextLine();
        try {
            WriteFileNIO(Filename);
        } catch (IOException ex) {
            Logger.getLogger(ReadFilesUsingNIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
